var express = require('express');
var router = express.Router();
var url = require("url");
var querystring = require("querystring");
var {
  keys, ivs, aesDecrypt
} = require("../utils")
var { Myuser, Movie } = require("../utils/model")
/* GET home page. */
router.get('/', function (req, res, next) {
  res.render('index', { title: 'Express', username: req.session.username });
});
router.get("/test", (req, res) => {
  res.send("test-test-test");
})
//登录
router.get("/login", (req, res) => {
  //  res.send("登录-success--login")
  const username = req.query.username ? aesDecrypt(req.query.username, keys, ivs) : ""
  console.log(username)
  console.log(keys)
  console.log(ivs)
  res.render("login", { username })
})

//退出登录
router.get("/logout", (req, res) => {
  //  销毁 session
  req.session.destroy(() => {
    res.redirect("/");
  });
})


//注册
router.get("/register", (req, res) => {
  res.render("register")
})


router.get("/mav", (req, res) => {

  if (req.session.username) {
    const query = req.query;
    var sort = {}
    var search = {}
    var keyword = query.keyword;
    if (keyword) {
      // 搜索
      search = {
        $or: [
          {
            title: new RegExp(keyword)
          },
          {
            year: new RegExp(keyword)
          },
          {
            'rating.average': new RegExp(keyword)
          },
          {
            'directors.name': new RegExp(keyword)
          }
        ]
      }
    } else {
      // 排序 
      sort = { ...query }
    }
    Movie.find(search, {
      _id: 0
    }).sort(sort).then(result => {
      res.render("mav", {
        username: req.session.username,
        result
      })
    })

  } else {
    res.send(`<script>alert('session已经过期或者失效,请重新登录');window.location.href='/login'</script>`)
  }
})

router.get("/about", (req, res) => {
  if (req.session.username) {
    Myuser.findOne({ username: req.session.username }).then(result => { console.log(result), res.render("about", { username: req.session.username, result }) })
  } else {
    res.send(`<script>alert('session已经过期或者失效,请重新登录');window.location.href='/login'</script>`)
  }
})

module.exports = router;
